package com.zFace.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.concurrent.CountDownLatch;

/**
 * 统计一台电脑的多个磁盘大小。现在有 C、D、E 三个磁盘
 * 要求是：
 * <p>
 * 第 1 个线程统计 C 盘的大小
 * 第 2 个线程统计 D 盘的大小
 * 第 3 个线程统计 E 盘的大小
 * 第 4 个线程里面得到 上面三个线程的 统计结果
 */
public class DIrSize {
	public static void main(String[] args) throws InterruptedException {
		DirTotalSize dirTotalSize = new DirTotalSize();
		CountDownLatch latch = new CountDownLatch(3);

		new Thread(new Tt(dirTotalSize, "/Users/zhangchuanqiang/Desktop/aa/1", latch)).start();
		new Thread(new Tt(dirTotalSize, "/Users/zhangchuanqiang/Desktop/aa/2", latch)).start();
		new Thread(new Tt(dirTotalSize, "/Users/zhangchuanqiang/Desktop/aa/3", latch)).start();

		latch.await();
		new Thread(new Total(dirTotalSize)).start();

	}

	static class Tt implements Runnable {

		private DirTotalSize dirTotalSize;
		private String path;
		private CountDownLatch countDownLatch;

		public Tt(DirTotalSize dirTotalSize, String path, CountDownLatch countDownLatch) {
			this.dirTotalSize = dirTotalSize;
			this.path = path;
			this.countDownLatch = countDownLatch;
		}

		@Override
		public void run() {
			try {
				dirTotalSize.add(FileUtils.sizeOfDirectory(new File(path)));
			} finally {
				countDownLatch.countDown();
			}
		}
	}

	static class Total implements Runnable {
		private DirTotalSize dirTotalSize;

		public Total(DirTotalSize dirTotalSize) {
			this.dirTotalSize = dirTotalSize;
		}

		@Override
		public void run() {
			dirTotalSize.getTotalSize();
		}
	}

	static class DirTotalSize {
		private long totalSize;

		public void add(long size) {
			totalSize += size;
		}

		public long getTotalSize() {
			System.out.println(totalSize);
			return totalSize;
		}
	}
}
